package com.jk.garden1.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jk.garden1.dao.BuildingDao;
import com.jk.garden1.dao.EsBuildingDao;
import com.jk.garden1.dao.FollowPeopleDao;
import com.jk.garden1.dao.LevelDao;
import com.jk.garden1.entity.BuildingEntity;
import com.jk.garden1.entity.FollowPeopleEntity;
import com.jk.garden1.entity.LevelEntity;
import com.jk.garden1.entity.VisitorEntity;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchResultMapper;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
import org.springframework.data.elasticsearch.core.aggregation.impl.AggregatedPageImpl;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.SearchQuery;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;

/**
 * 楼宇维护
 */
@Service
public class BuildingService {
    @Autowired
    private BuildingDao buildingDao;
    @Autowired
    private FollowPeopleDao followPeopleDao;
    @Autowired
    private LevelDao levelDao;
    @Autowired
    private ElasticsearchRestTemplate es;
    @Autowired
    private EsBuildingDao esBuildingDao;
    //定义验证码
    public static String charactercode = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    /**
     * 查询全部
     */
    public List<BuildingEntity> selectListBuilding(BuildingEntity buildingEntity) {
        Map map=new HashMap();
        if (buildingEntity.getBuildingname() !=null && buildingEntity.getBuildingname() !="")
            map.put("buildingname",buildingEntity.getBuildingname());
        if (buildingEntity.getBuildingcode() !=null && buildingEntity.getBuildingcode() !="")
            map.put("buildingcode",buildingEntity.getBuildingcode());

//        return parkDao.selectByMap(map);
        return buildingDao.selectByMap(map);
    }
    /**
     * 添加楼宇
     */
    public void addBuilding(BuildingEntity buildingEntity) {
        StringBuilder stringBuilder = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < 6; i++) {
            stringBuilder.append(charactercode.charAt(random.nextInt(6)));
        }
        buildingEntity.setBuildingcode(stringBuilder.toString());
        buildingEntity.setState("正常");
        buildingDao.insert(buildingEntity);
        int floor = Integer.parseInt(buildingEntity.getFloor());
        for (int i = 1; i <= floor; i++) {
            LevelEntity levelEntity = new LevelEntity();
            levelEntity.setPid(buildingEntity.getId());
            levelEntity.setLevel("F0"+i+"层");
            levelDao.insert(levelEntity);
        }
    }

    public void updateById(Integer id) {
        BuildingEntity buildingEntity = buildingDao.selectById(id);
        buildingEntity.setState("已停用");
        buildingDao.updateById(buildingEntity);
    }

    /**
     * 新建索引
     */
    public void create(){
        es.createIndex(BuildingEntity.class);
        QueryWrapper wp=new QueryWrapper();
        List<BuildingEntity> list = buildingDao.selectList(wp);
        list.forEach(a -> {
            esBuildingDao.save(a);
        });
    }

    /**
     * es高亮查询
     * @param building
     * @return
     */
    public List<BuildingEntity> queryEsList(BuildingEntity building) {
        if (es.indexExists(BuildingEntity.class)){
            create();
        }
        NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
        //楼宇代码精确查
        if(StringUtils.hasText(building.getBuildingcode())){
            nativeSearchQueryBuilder.withQuery(QueryBuilders.termQuery("buildingcode",building.getBuildingcode()));
        }
        //楼宇名称模糊查
        if(StringUtils.hasText(building.getBuildingname())){
            nativeSearchQueryBuilder.withQuery(QueryBuilders.matchQuery("buildingname",building.getBuildingname()));
        }
        //负责人姓名模糊查
        if(StringUtils.hasText(building.getPrincipalname())){
            nativeSearchQueryBuilder.withQuery(QueryBuilders.matchQuery("principalname",building.getPrincipalname()))
                    .withHighlightFields(new HighlightBuilder.Field("principalname").preTags("<font color='red'>").postTags("</font>"));
        }
        SearchQuery build = nativeSearchQueryBuilder.build();
        if(StringUtils.hasText(building.getPrincipalname())){
            AggregatedPage<BuildingEntity> employeeEntity = es.queryForPage(build, BuildingEntity.class, new SearchResultMapper() {
                @Override
                public <T> AggregatedPage<T> mapResults(SearchResponse searchResponse, Class<T> aClass, Pageable pageable) {
                    SearchHits hits = searchResponse.getHits();
                    List list = new ArrayList();
                    for (SearchHit hit : hits) {
                        Map<String, Object> sourceAsMap = hit.getSourceAsMap();
                        Map<String, HighlightField> highlightFields = hit.getHighlightFields();
                        sourceAsMap.put("principalname", highlightFields.get("principalname").getFragments()[0].toString());
                        list.add(sourceAsMap);
                    }
                    return new AggregatedPageImpl<>(list);
                }
                @Override
                public <T> T mapSearchHit(SearchHit searchHit, Class<T> aClass) {
                    return null;
                }
            });
            return employeeEntity.getContent();
        }else{
            List<BuildingEntity> list2 = es.queryForList(build, BuildingEntity.class);
            return  list2;
        }
    }

    public FollowPeopleEntity findSuiFangList(Integer visitorid) {
        FollowPeopleEntity followPeopleEntity = followPeopleDao.selectById(visitorid);
        return followPeopleEntity;
    }
}
